package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.*;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IAiRecordingMainService;
import com.ruoyi.system.util.xfyun.utils.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IAiRecordingChildService;

/**
 * AI录音子，记录每一条Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-06
 */
@Service
public class AiRecordingChildServiceImpl implements IAiRecordingChildService
{
    @Autowired
    private AiRecordingChildMapper aiRecordingChildMapper;
    @Autowired
    private AiRecordingMainMapper aiRecordingMainMapper;
    @Autowired
    private AiDeepseekAnswerMapper aiDeepseekAnswerMapper;
    @Autowired
    private AiRecordingDuanMapper aiRecordingDuanMapper;
    @Autowired
    private AiDeepseekSpokesmanMapper aiDeepseekSpokesmanMapper;
    @Autowired
    private IAiRecordingMainService aiRecordingMainService;
    /**
     * 查询AI录音子，记录每一条
     *
     * @param id AI录音子，记录每一条主键
     * @return AI录音子，记录每一条
     */
    @Override
    public AiRecordingChild selectAiRecordingChildById(Long id)
    {
        return aiRecordingChildMapper.selectAiRecordingChildById(id);
    }

    /**
     * 查询AI录音子，记录每一条列表
     *
     * @param aiRecordingChild AI录音子，记录每一条
     * @return AI录音子，记录每一条
     */
    @Override
    public List<AiRecordingChild> selectAiRecordingChildList(AiRecordingChild aiRecordingChild)
    {
        return aiRecordingChildMapper.selectAiRecordingChildList(aiRecordingChild);
    }


    public List<AiRecordingChild> listByMainIdToSpear(AiRecordingChild aiRecordingChild){
        List<AiRecordingChild>  aiRecordingChildList=  aiRecordingChildMapper.listByMainIdToSpear(aiRecordingChild);
      return aiRecordingChildList;
    }


    public List<AiRecordingDuan> selectRecordDuanVo(AiRecordingChild aiRecordingChild){
        Long mainId=  aiRecordingChild.getMainId();
        AiRecordingMain aiRecordingMain=   aiRecordingMainMapper.selectAiRecordingMainById(mainId);
        String status= aiRecordingMain.getStatus();
        if (status.equals("1") || status.equals("2")){
            List<AiRecordingDuan> aiRecordingDuanList=new ArrayList<AiRecordingDuan>();
            return aiRecordingDuanList;
        }
        String batchId=  aiRecordingChild.getBatchId();
        List<AiRecordingDuan> aiRecordingDuanList;
        if (status.equals("4") || status.equals("5") ||status.equals("6")){
            AiRecordingDuan aiRecordingDuan=new AiRecordingDuan();
            aiRecordingDuan.setMainId(mainId);
            aiRecordingDuan.setBatchId(batchId);
           aiRecordingDuanList=  aiRecordingDuanMapper.selectAiRecordingDuanListBy(aiRecordingDuan);
            aiRecordingDuanList.forEach(duan->{
                List<AiRecordingChild>  aiRecordingChildList=  aiRecordingChildMapper.selectChildBySpokes(duan);
//                aiRecordingChildList.forEach(child->{
//                     if (child.getFilePath().contains(".wav")){
//                         child.setFilePath(child.getFilePath().split(".wav")[0]);
//                     }
//                });


                duan.setAiRecordingChildList(aiRecordingChildList);
//                AiDeepseekAnswer aiDeepseekAnswer=new AiDeepseekAnswer();
//                aiDeepseekAnswer.setMainId(mainId);
//                aiDeepseekAnswer.setDuanId(duan.getId());
//                List<AiDeepseekAnswer> aiDeepseekAnswerList= aiDeepseekAnswerMapper.selectAiDeepseekAnswerList(aiDeepseekAnswer);
//                //根据scoreYear字段进行分组
//                Map<String, List<AiDeepseekAnswer>> map = aiDeepseekAnswerList.stream().collect(
//                        Collectors.groupingBy(
//                                score -> score.getBatchId()
//                        ));
//                duan.setAnswerMap(map);
//todo  这个没用到批次了，改成单次了
//                duan.setAiDeepseekAnswerList(aiDeepseekAnswerList);

//                aiRecordingDuanList.add(duan);
            });
        }else{
            aiRecordingDuanList = new ArrayList<AiRecordingDuan>();
          String response=  aiRecordingMain.getRangeStrs();
            if (response.contains("以下是输出结果")){
                response=  response.split("以下是输出结果")[1].replace(":", "").replace("：", "").replaceAll("\\s", "");
            }
            List<Long>     longList = Arrays.stream(response.split(",")).map(String::trim) // 去掉空格
                    .map(Long::valueOf)
                    .collect(Collectors.toList());

            for (int i = 0; i < longList.size(); i++) {
                AiRecordingDuan aiRecordingDuan=new AiRecordingDuan();
                String range="";
                aiRecordingChild.setBg(longList.get(i));
                range=longList.get(i)+"-";
                if (i!=longList.size()-1){
                    aiRecordingChild.setEg(longList.get(i+1));
                    range=range+longList.get(i+1);
                }else{
                    range=range+"--";
                    aiRecordingChild.setEg(null);
                }
                List<AiRecordingChild> aiRecordingChildList=   aiRecordingChildMapper.selectChildByMainSelFile(aiRecordingChild);
                aiRecordingDuan.setDuan(range);
                aiRecordingDuan.setAiRecordingChildList(aiRecordingChildList);
                aiRecordingDuanList.add(aiRecordingDuan);
            }
        }
        return aiRecordingDuanList;
    }


    /**
     * 新增AI录音子，记录每一条
     *
     * @param aiRecordingChild AI录音子，记录每一条
     * @return 结果
     */
    @Override
    public int insertAiRecordingChild(AiRecordingChild aiRecordingChild)
    {
        aiRecordingChild.setCreateTime(DateUtils.getNowDate());
        return aiRecordingChildMapper.insertAiRecordingChild(aiRecordingChild);
    }

    /**
     * 修改AI录音子，记录每一条
     *
     * @param aiRecordingChild AI录音子，记录每一条
     * @return 结果
     */
    @Override
    public int updateAiRecordingChild(AiRecordingChild aiRecordingChild)
    {
        aiRecordingChild.setUpdateTime(DateUtils.getNowDate());
        return aiRecordingChildMapper.updateAiRecordingChild(aiRecordingChild);
    }

//    public int updateAiRecordingChildMatch(AiRecordingMain aiRecordingMain){
////        if ()
//        aiRecordingMainMapper.updateAiRecordingMain(aiRecordingMain);
//
//        aiRecordingMain.getRecordDuanVoList().forEach(child->{
//            if (!child.getChildList().isEmpty()){
//                child.getChildList().forEach(childdd->{
//                    if (childdd.getSpeakerName()!=null && !childdd.getSpeakerName().isEmpty()){
//                        aiRecordingChildMapper.updateAiRecordingChildByIdSpare(childdd);
//                    }
//                });
//            }
//        });
//        return 1;
//    }
    @Override
    public AjaxResult updateAiRecordingChildDuan(AiRecordingMain aiRecordingMain){
        Long mainId=  aiRecordingMain.getId();
        AiRecordingMain aiRecordingMainNow=  aiRecordingMainMapper.selectAiRecordingMainById(mainId);
        String status=aiRecordingMainNow.getStatus();
        if (!status.equals("2") && !status.equals("3")){
            AjaxResult.error("该条录音存在正在分析中的数据，暂无法修改场景数据");
        }
        aiRecordingMain.setStatus("4");
        String batchId=(new SnowflakeIdGenerator(1, 1).nextId())+"";
        aiRecordingMain.setBatchId(batchId);
        aiRecordingMainMapper.updateAiRecordingMain(aiRecordingMain);
        String  orderId=  aiRecordingMainNow.getOrderId();
        List<AiRecordingDuan> aiRecordingDuanList=new ArrayList<>();


        AtomicReference<Double> sumTime= new AtomicReference<>((double) 0);
        aiRecordingMain.getAiRecordingDuanList().forEach(duan->{
            duan.setUserId(aiRecordingMainNow.getUserId());
//            duan.setDeptId(SecurityUtils.getUserId());
            duan.setMainId(mainId);
            duan.setStatus("1");
            duan.setCreateTime(new Date());

//            child.setTime(child.getTime());
            duan.setOrderId(orderId);
//            aiRecordingDuan.setCreateTime(child.getCreateTime());
//            child.setCreateBy(SecurityUtils.getUsername());
            duan.setBatchId(batchId);
            aiRecordingDuanMapper.insertAiRecordingDuan(duan);
          Long duanId=  duan.getId();
            List<AiDeepseekSpokesman> aiDeepseekSpokesmanList = duan.getAiDeepseekSpokesmanList();
            if (!aiDeepseekSpokesmanList.isEmpty()){
                duan.getAiDeepseekSpokesmanList().forEach(spoke->{
                    spoke.setMainId(mainId);
//                    spoke.setRangeStr();
                    spoke.setDuanId(duanId);
                    spoke.setBatchId(batchId);
                    aiDeepseekSpokesmanMapper.insertAiDeepseekSpokesman(spoke);
                });
            }
            aiRecordingDuanList.add(duan);
            List<AiRecordingChild>  aiRecordingChildList=  aiRecordingChildMapper.selectChildBySpokes(duan);
            final String[] wenzi = {""};
            aiRecordingChildList.forEach(childdd->{
                if (childdd.getTranscript()!=null && !childdd.getTranscript().isEmpty()){
                    wenzi[0] = wenzi[0] +" "+childdd.getTranscript();
                }
            });
            int dividend=1;
            long count=0;
            double   time=0;
            String languages= aiRecordingMainNow.getLanguages();
            if (languages.equals("cn")){
                count = countChineseCharacters(wenzi[0]);
                dividend=250;
            }else if (languages.equals("en")){
                count = countEnglishWords(wenzi[0]);
                dividend=120;
            }
            time= (double) count/dividend;
            sumTime.set(sumTime.get() + time);
            duan.setValidTime(time);
            aiRecordingDuanMapper.updateAiRecordingDuan(duan);
        });
//        aiRecordingMain.setValidTime(sumTime.get());
//        aiRecordingMainMapper.updateAiRecordingMain(aiRecordingMain);
        // 创建一个新线程执行异步任务
        Thread thread = new Thread(() -> {
            // 模拟耗时操作
            aiRecordingDuanList.forEach(duan->{
                try {
                    aiRecordingMainService.deepseekParse(duan);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
            System.out.println("异步任务完成");
        });

        // 启动线程
        thread.start();

        return AjaxResult.success();
    }
//    public static void main(String[] args) {
//        String text = "Hello, worlrd! This irs a terst strring.";
//        long count = countEnglishWords(text);
//        System.out.println("英文单词数量: " + count);
//    }

    public static long countEnglishWords(String text) {
        if (text == null || text.isEmpty()) {
            return 0;
        }

        // 去除标点符号并按空格分割
        return Arrays.stream(text.replaceAll("[^a-zA-Z\\s]", "").split("\\s+"))
                .filter(word -> !word.isEmpty())
                .count();
    }

    public static int countChineseCharacters(String text) {
        // 使用正则表达式匹配中文字符
        String chineseRegex = "[\u4e00-\u9fa5]";
        int count = 0;

        for (int i = 0; i < text.length(); i++) {
            String character = String.valueOf(text.charAt(i));
            if (character.matches(chineseRegex)) {
                count++;
            }
        }

        return count;
    }



//    public  void    deepseekParse( List<AiRecordingDuan> aiRecordingDuanList){
//
//
//        // 创建一个新线程执行异步任务
//        Thread thread = new Thread(() -> {
//            // 模拟耗时操作
//            aiRecordingDuanList.forEach(duan->{
//                try {
//                    aiRecordingMainService.deepseekParse(duan);
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }
//            });
//            System.out.println("异步任务完成");
//        });
//
//        // 启动线程
//        thread.start();
//
//    }


    /**
     * 批量删除AI录音子，记录每一条
     *
     * @param ids 需要删除的AI录音子，记录每一条主键
     * @return 结果
     */
    @Override
    public int deleteAiRecordingChildByIds(Long[] ids)
    {

        AiRecordingChild aiRecordingChild=new AiRecordingChild();
        aiRecordingChild.setId(ids[0]);
        aiRecordingChild.setDelFlag("1");
        return aiRecordingChildMapper.updateAiRecordingChild(aiRecordingChild);

//        return aiRecordingChildMapper.deleteAiRecordingChildByIds(ids);
    }

    /**
     * 删除AI录音子，记录每一条信息
     *
     * @param id AI录音子，记录每一条主键
     * @return 结果
     */
    @Override
    public int deleteAiRecordingChildById(Long id)
    {
        return aiRecordingChildMapper.deleteAiRecordingChildById(id);
    }
}
